import 'package:fast_build/common/common.dart';
import 'package:fast_build/common/theme/theme_util.dart';
import 'package:fast_build/common/utils.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:hk_base/hk_base.dart';

import 'tab_controller.dart';

class TabPage extends GetView<TabPageController> {
  const TabPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    DateTime? lastPopTime;
    return Scaffold(
      resizeToAvoidBottomInset: false,
      floatingActionButton: FloatingActionButton(
        onPressed: () {},
        hoverColor: Colors.transparent,
        splashColor: Colors.transparent,
        foregroundColor: Colors.transparent,
        elevation: 0.3,
        hoverElevation: 0.0,
        focusElevation: 0.0,
        highlightElevation: 0.0,
        backgroundColor: Get.theme.backgroundColor,
        child: HkZoomBtn(
          Obx(() => Image.asset(
                controller.tabIndex.value == 2
                    ? 'assets/tab/community_opt.png'
                    : 'assets/tab/community.png',
                width: 66.w,
                height: 66.w,
              )),
          onTap: () {
            controller.tabIndex.value = 2;
          },
        ),
      ),
      floatingActionButtonLocation: CustomFloatingActionButtonLocation(
          FloatingActionButtonLocation.centerDocked, 0, 5.w),
      body: WillPopScope(
          onWillPop: () async {
            if (lastPopTime == null ||
                DateTime.now().difference(lastPopTime!) > const Duration(seconds: 1)) {
              lastPopTime = DateTime.now();
              hkShowToast("再按一次退出");
              return Future.value(false);
            } else {
              lastPopTime = DateTime.now();
              // 退出app
              return Future.value(true);
            }
          },
          child: Obx(() => IndexedStack(
                index: controller.tabIndex.value,
                children: controller.tabViewList,
              ))),
      bottomNavigationBar: BottomAppBar(
        shape: const CircularNotchedRectangle(),
        elevation: 2,
        color: Colors.white,
        child: SizedBox(
            height: 56.0,
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: controller.tabList
                    .asMap()
                    .entries
                    .map((item) => _buildTabBar(item))
                    .toList())),
      ),
    );
  }

  Widget _buildTabBar(item) {
    return HkZoomBtn(
      Obx(() => Stack(
            children: [
              Container(
                width: 56.0,
                height: 56.0,
                alignment: Alignment.center,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    AnimatedCrossFade(
                        firstChild: Image.asset(
                          item.value["selectImg"],
                          width: 48.w,
                          height: 48.w,
                        ),
                        secondChild: Image.asset(
                          item.value["img"],
                          width: 48.w,
                          height: 48.w,
                        ),
                        crossFadeState: controller.tabIndex.value == item.key
                            ? CrossFadeState.showFirst
                            : CrossFadeState.showSecond,
                        duration: const Duration(milliseconds: 150)),
                    Text(
                      "${item.value["title"]}",
                      style: controller.tabIndex.value == item.key
                          ? TextStyle(
                              fontSize: 22.sp,
                              color: Get.theme.textTheme.headline3!.color,
                              fontWeight: FontWeight.bold)
                          : TextStyle(
                              fontSize: 22.sp,
                              color: Get.theme.textTheme.headline4!.color),
                    )
                  ],
                ),
              ),
              controller.unReadNum.value == 0 || item.key != 3
                  ? Container()
                  : Positioned(
                      right: 6.w,
                      top: 2.w,
                      height: 15.w,
                      child: Container(
                        height: 15.w,
                        constraints: BoxConstraints(minWidth: 15.w),
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                            color: Get.theme.textTheme.subtitle1!.color,
                            borderRadius: BorderRadius.circular(15.w)),
                        child: Obx(() => Text(
                              '${controller.unReadNum.value + controller.unreadCount.value}',
                              style: TextStyle(
                                  fontSize: 11.sp,
                                  color: Get.theme.textTheme.headline5!.color),
                            )),
                      )),
              controller.unreadCount.value == 0 ||
                      item.key != 3 ||
                      controller.unReadNum.value != 0
                  ? Container()
                  : Positioned(
                      right: 10.w,
                      top: 4.w,
                      width: 10.w,
                      height: 10.w,
                      child: Container(
                          constraints: BoxConstraints(minWidth: 15.w),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Get.theme.textTheme.subtitle1!.color,
                              borderRadius: BorderRadius.circular(15.w))))
            ],
          )),
      onTap: () {
        controller.tabIndex.value = item.key;
      },
    );
  }

  void _changeSkin() {
    ThemeUtil.changeTheme();
  }

  void _showUiTips() {
    // hkShowToast("点我~");
    LoadingUtils.show(msg: "开始抽奖啦，请稍等~");
    hkSetTimeout(() {
      LoadingUtils.dismiss();
      hkShowToast('恭喜你中奖了~');
    }, const Duration(microseconds: 1000));
  }

  void _getMockData() async {
    var responseJson = await HkUtils.mock(url: 'mock');
    HkLog.d("data>>>>$responseJson");
  }

  void _showDialog(context) {
    Utils.showCustomDialog();
    return;
    UiUtils.showCommonDialog(
      context,
      title: '请确认继续',
      message: 'IOS支付的用户，匹配失败后无法退款。但可以最高匹配成功率免费报名下一期。',
      cancelTitle: '取消',
      confirmTitle: '继续报名',
      confirmCallback: () {
        hkShowToast('成功~');
      },
    );
  }
}

class CustomFloatingActionButtonLocation extends FloatingActionButtonLocation {
  FloatingActionButtonLocation location;
  double offsetX; // X方向的偏移量
  double offsetY; // Y方向的偏移量
  CustomFloatingActionButtonLocation(this.location, this.offsetX, this.offsetY);

  @override
  Offset getOffset(ScaffoldPrelayoutGeometry scaffoldGeometry) {
    Offset offset = location.getOffset(scaffoldGeometry);
    return Offset(offset.dx + offsetX, offset.dy + offsetY);
  }
}
